package hn.cch.druid.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.support.JpaEntityInformation;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support
        .RepositoryFactorySupport;

import javax.persistence.EntityManager;
import java.io.Serializable;

/**
 * @author CCH
 * @version 2018.08.30
 */
public class DruidRepositoryFactoryBean<S extends JpaRepository<T, ID>, T, ID
        extends Serializable> extends JpaRepositoryFactoryBean<S, T, ID> {

    protected RepositoryFactorySupport createRepositoryFactory(EntityManager
                                                                       entityManager) {
        return new DruidRepositoryFactory<T, ID>(entityManager);
    }

    private static class DruidRepositoryFactory<T, ID extends Serializable>
            extends JpaRepositoryFactory {

        private EntityManager entityManager;

        public DruidRepositoryFactory(EntityManager entityManager) {
            super(entityManager);
            this.entityManager = entityManager;
        }

        protected DruidRepository getDruidRepository(RepositoryMetadata
                                                             repositoryMetadata) {
            JpaEntityInformation<T, Serializable> jpaEnityInformation =
                    (JpaEntityInformation<T, Serializable>)
                            getEntityInformation(repositoryMetadata
                                    .getDomainType());
            return new DruidRepositoryImpl<T, ID>(jpaEnityInformation,
                    entityManager);
        }

        protected Class<?> getRepositoryBaseClass(RepositoryMetadata
                                                          repositoryMetadata) {
            return DruidRepositoryImpl.class;
        }
    }
}
